package com.ccsoft.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author chanchaw
 * @create 2022-07-18 8:03
 */
public class ServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
        if(httpObject instanceof HttpRequest){
            String hoType = httpObject.getClass().toString();
            String clientAddr = ctx.channel().remoteAddress().toString();
            System.out.println("httpObject类型：" + hoType + ",客户端地址：" + clientAddr);

            // 过滤掉指定URI的请求
            HttpRequest req = (HttpRequest)httpObject;
            URI uri = new URI(req.uri());
            System.out.println("uri:" + uri);

            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("服务端过滤掉请求：/favicon.ico。不响应客户端请求");
                return;
            }

            ByteBuf sendMsgBuf = Unpooled.copiedBuffer("你好，我是服务器", CharsetUtil.UTF_8);

            // 构建响应对象
            FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, sendMsgBuf);
            res.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            res.headers().set(HttpHeaderNames.CONTENT_LENGTH,sendMsgBuf.readableBytes());

            // 向客户端发送消息
            ctx.writeAndFlush(res);
        }
    }
}
